import { ReportContent, PresetSencePlugin, EventName } from '@/types';

interface ResponseHeader {
  'server-timing'?: string;
}

export const serverTiming: PresetSencePlugin = (apiTrack, dataSet) => {
  const timing = (dataSet.response_header as ResponseHeader)?.['server-timing'];
  if (!timing) return;
  const { api_path, log_id } = dataSet;
  const reportObject: Required<ReportContent<string>> = {
    categories: {
      api_path,
      log_id: log_id || '-',
    },
    metrics: {},
  };
  timing.split(',').forEach((item) => {
    const [key, value] = item.split('=');
    const formatKey = key.replace(/;\s?/, '-');
    // 是否是数值
    /\d+/.test(value)
      ? (reportObject.metrics[formatKey] = Number(value))
      : (reportObject.categories[formatKey] = value);
  });
  apiTrack?.reporter.sendLog(EventName.ServerTiming, reportObject);
};
